package com.sparrow.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by wancheng on 2019/2/15.
 */
@Service
public class PackageScan implements ResourceLoaderAware {

    private final String BASE_CLASS_PATH_CONTROLLER = "classpath*:com/sparrow/controller/**/*.class";

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 获取包名下所有的类
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public List<Class<?>> getControllerClass() throws IOException, ClassNotFoundException {
        List<Class<?>> res = new ArrayList<>();
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = resolver.getResources(BASE_CLASS_PATH_CONTROLLER);
        for (Resource r : resources) {
            MetadataReader reader = metaReader.getMetadataReader(r);
            Class<?> clz = Class.forName(reader.getClassMetadata().getClassName());
            res.add(clz);
            System.out.println("controller:" + clz.getName());
        }
        return res;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}
